#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <fstream>

using namespace std;

class SearchTree {
public:
	struct node {
		string word;
		int cost, best;
		int next[10];
	};
	
	int cur_pos;
	vector <node> v;
	
	SearchTree(){
		cur_pos = 0;
		v.resize(1);
		v[0].word = "";
		v[0].best = -1;
		for(int i = 0; i < 10; i++){
			v[0].next[i] = -1;
		}
	}
	
	int GetCode(char ch){
		if(ch >= 'a' && ch <= 'c'){
			return 2;
		}
		if(ch >= 'd' && ch <= 'f'){
			return 3;
		}
		if(ch >= 'g' && ch <= 'i'){
			return 4;
		}
		if(ch >= 'j' && ch <= 'l'){
			return 5;
		}
		if(ch >= 'm' && ch <= 'o'){
			return 6;
		}
		if(ch >= 'p' && ch <= 's'){
			return 7;
		}
		if(ch >= 't' && ch <= 'v'){
			return 8;
		}
		return 9;
	}
	
	void AddWord(string &s, int pos, int len, int cost){
		if(len >= (int)s.size()){
			if(v[pos].word == "" || cost > v[pos].cost){
				v[pos].word = s;
				v[pos].cost = cost;
			}
			v[pos].best = pos;
			for(int i = 0; i < 10; i++){
				if(v[pos].next[i] != -1 && v[v[v[pos].next[i]].best].cost > v[v[pos].best].cost){
					v[pos].best = v[v[pos].next[i]].best;
				}
			}
			return;
		}
		int code = GetCode(s[len]);
		if(v[pos].next[code] == -1){
			v.push_back(node());
			v.back().word = "";
			v.back().best = -1;
			for(int i = 0; i < 10; i++){
				v.back().next[i] = -1;
			}
			v[pos].next[code] = (int)v.size() - 1;
		}
		AddWord(s, v[pos].next[code], len + 1, cost);
		if(v[pos].best == -1 || v[v[v[pos].next[code]].best].cost > v[v[pos].best].cost){
			v[pos].best = v[v[pos].next[code]].best;
		}
	}
	
	void AddWord(string s, int cost){
		AddWord(s, 0, 0, cost);
	}
	
	void Clear(){
		cur_pos = 0;
	}
	
	bool Find(char ch){
		if(!(ch >= '0' && ch <= '9')){
			cur_pos = -1;
			cerr << "incorrect symbol" << endl;
			return false;
		}
		if(cur_pos == -1){
			cerr << "not found" << endl;
			return false;
		}
		int code = ch - '0';
		if(v[cur_pos].next[code] == -1){
			cerr << "not found" << endl;
			cur_pos = -1;
			return false;
		}
		cur_pos = v[cur_pos].next[code];
		cout << v[v[cur_pos].best].word << endl;
		return true;
	}
	
};

int main(int argc, char **argv){
	SearchTree T;
	ifstream in;
	in.open(argv[1]);
	string s;
	int cost;
	char tmp;
	while(in >> s >> cost >> tmp){
		T.AddWord(s, cost);
	}
	char ch;
	while(cin >> ch){
		if(ch >= '0' && ch <= '9'){
			T.Find(ch);
		}
		else{
			T.Clear();
		}
	}
	return 0;
}
